package com.cetcs.kmga.dataManager.controller;

import com.cetcs.kmga.common.*;
import com.cetcs.kmga.dataManager.annotation.LogAnnotation;
import com.cetcs.kmga.dataManager.entity.dataManager.ClientDBCluster;
import com.cetcs.kmga.dataManager.entity.dataManager.Resrc;
import com.cetcs.kmga.dataManager.entity.dataManager.vi.ClientDBClusterVi;
import com.cetcs.kmga.dataManager.entity.dataManager.vi.ClientDBForClusterVi;
import com.cetcs.kmga.dataManager.entity.global.CodeAndValue;
import com.cetcs.kmga.dataManager.entity.global.LogLevelEnum;
import com.cetcs.kmga.dataManager.entity.global.LogTypeEnum;
import com.cetcs.kmga.dataManager.entity.sysManager.LocalServerInfo;
import com.cetcs.kmga.dataManager.entity.sysManager.vi.LocalServerInfoVi;
import com.cetcs.kmga.dataManager.entity.sysManager.vi.RecordsVi;
import com.cetcs.kmga.dataManager.entity.sysManager.vi.SysEmailSerConfVi;
import com.cetcs.kmga.dataManager.entity.sysManager.vo.ServerStatusVo;
import com.cetcs.kmga.dataManager.entity.sysManager.vo.SpaceAccountedVo;
import com.cetcs.kmga.dataManager.service.dataManager.DataManagerService;
import com.cetcs.kmga.dataManager.service.sysManager.ClientDBService;
import com.cetcs.kmga.dataManager.service.sysManager.SysManagerService;
import com.cetcs.kmga.dataManager.util.ExcelUtil;
import com.google.common.collect.Lists;
import org.apache.commons.io.FileUtils;
import org.apache.phoenix.shaded.org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 类注释
 * 日志管理
 *
 * @author yyangs
 * @version V1.0 创建时间：2017-08-30 13:40
 *          Copyright 2017 by CETC
 */
@RestController
@RequestMapping("/sysManager")
public class SysManagerController extends BaseController {

    @Autowired
    private SysManagerService sysManagerService;
    @Autowired
    private ClientDBService clientDBService;
    @Autowired
    private DataManagerService dataManagerService;

    /****************
     **** 系统信息 **
     ***************/


    /***=============================系统信息=================**/


    /**
     * 获取本地的服务器信息
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "系统管理-系统信息-系统信息", logType = LogTypeEnum.业务日志, description = "获取本地的服务器信息", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getLocalServiceInfo", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getLocalServiceInfo() {
        try {
            Data data = new Data( );
            LocalServerInfo localServerInfo = sysManagerService.getLocalServiceInfo(data);
            return this.ok(localServerInfo);
        } catch (Exception e) {
            e.printStackTrace( );
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 修改本地的服务器信息
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "系统管理-系统信息-系统信息", logType = LogTypeEnum.业务日志, description = "修改本地的服务器信息", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/updateLocalServiceInfo", method = RequestMethod.POST, produces = {"application/json", "application/xml"})
    public BaseResponse updateLocalServiceInfo(@Valid @RequestBody LocalServerInfoVi localServerInfoVi, BindingResult bindingResult) {
        try {
            Data data = new Data( );
            if (localServerInfoVi.getAdminName( ) != null) {
                data.put("adminName", localServerInfoVi.getAdminName( ));
            }
            if (localServerInfoVi.getAdminPhone( ) != null) {
                data.put("adminPhone", localServerInfoVi.getAdminPhone( ));
            }
            if (localServerInfoVi.getIp( ) != null) {
                data.put("serverIp", localServerInfoVi.getIp( ));
            }
            if (localServerInfoVi.getServerLocation( ) != null) {
                data.put("serverLocaltion", localServerInfoVi.getServerLocation( ));
            }
            if (localServerInfoVi.getServerName( ) != null) {
                data.put("serverName", localServerInfoVi.getServerName( ));
            }
            if (localServerInfoVi.getServerVersion( ) != null) {
                data.put("serverVersion", localServerInfoVi.getServerVersion( ));
            }
            Integer result = sysManagerService.updateLocalServiceInfo(data);
            return this.ok(result);
        } catch (Exception e) {
            e.printStackTrace( );
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 获取本机的服务器状态
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "系统管理-系统信息-系统信息", logType = LogTypeEnum.业务日志, description = "获取本机的服务器状态", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getServiceStatus", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getServiceStatus() {
        try {
            Data data = new Data( );
            ServerStatusVo serviceStatusVo = sysManagerService.getServiceStatus(data);
            return this.ok(serviceStatusVo);
        } catch (Exception e) {
            e.printStackTrace( );
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /****************
     **** 数据管理 **
     ***************/


    /***=============================磁盘清理=================**/


    /**
     * 获取本机的空间占比数据
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "系统管理-数据管理-磁盘清理", logType = LogTypeEnum.业务日志, description = "获取本机的空间占比数据", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getLocalSpaceAccounted", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getLocalSpaceAccounted() {
        try {
            Data data = new Data( );
            List<SpaceAccountedVo> spaceAccountedVos = sysManagerService.getLocalSpaceAccounted(data);
            for (int i = 0; i < spaceAccountedVos.size( ); i++) {
                spaceAccountedVos.get(i).setId(i + 1);
            }
            return this.ok(spaceAccountedVos);
        } catch (Exception e) {
            e.printStackTrace( );
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 获取监管平台的清理记录 分页
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "系统管理-数据管理-磁盘清理", logType = LogTypeEnum.业务日志, description = "获取监管平台的清理记录列表", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getCleanRecordsByPage", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getCleanRecordsByPage(WebRequest request,
                                              @RequestParam(required = false, defaultValue = "1") int page,
                                              @RequestParam(required = false, defaultValue = "5") int pageSize) {
        try {
            Data data = getParam(request);
            Page pageList = sysManagerService.getCleanRecordsByPage(data);
            return this.ok(pageList);
        } catch (Exception e) {
            e.printStackTrace( );
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 添加监管平台的清理记录
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "系统管理-数据管理-磁盘清理", logType = LogTypeEnum.业务日志, description = "添加监管平台的清理记录", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/addCleanRecords", method = RequestMethod.POST, produces = {"application/json", "application/xml"})
    public BaseResponse addCleanRecords(@Valid @RequestBody RecordsVi recordsVi, BindingResult bindingResult) {
        try {
            Data data = new Data( );
            String message = "";
            String logLevel = "";
            if (recordsVi.getSjfw( ) != null && recordsVi.getSjfw( ).size( ) > 0) {
                message += "数据访问日志:";
                String temp = "";
                for (String string : recordsVi.getSjfw( )) {
                    temp += "," + string;
                }
                message += temp.substring(1) + ";";
            }
            if (recordsVi.getSjtm( ) != null && recordsVi.getSjtm( ).size( ) > 0) {
                message += "数据脱敏日志:";
                String temp = "";
                for (String string : recordsVi.getSjtm( )) {
                    temp += "," + string;
                }
                message += temp.substring(1) + ";";
            }
            if (recordsVi.getSjyy( ) != null && recordsVi.getSjyy( ).size( ) > 0) {
                message += "数据运维日志:";
                String temp = "";
                for (String string : recordsVi.getSjyy( )) {
                    temp += "," + string;
                }
                message += temp.substring(1) + ";";
            }
            if (recordsVi.getXtrz( ) != null && recordsVi.getXtrz( ).size( ) > 0) {
                message += "系统日志:";
                String temp = "";
                for (String string : recordsVi.getXtrz( )) {
                    temp += "," + string;
                }
                message += temp.substring(1) + ";";
            }
            if (recordsVi.getRzdj( ) != null && recordsVi.getRzdj( ).size( ) > 0) {
                logLevel += "日志等级:";
                String temp = "";
                for (String string : recordsVi.getRzdj( )) {
                    temp += "," + string;
                }
                logLevel += temp.substring(1) + ";";
            }
            //日志等级
            data.put("logLevel", logLevel);
            //日志类型
            data.put("logType", message);
            data.put("operatorUsr", "admin");
            //操作时间
            data.put("operatorTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date( )));
            data.put("starTime", recordsVi.getStartTime( ));
            data.put("endTime", recordsVi.getStartEnd( ));

            //开始和结束时间

            Integer result = sysManagerService.addCleanRecords(data);
            if (result > 0) {
                return this.ok(result);
            } else {
                return this.error("请检查数据，添加失败！");
            }
        } catch (Exception e) {
            e.printStackTrace( );
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /*********************************************客户端**************************************************************/
    /*************************
     *********客户端类型配置***
     ************************/

    /**
     * 获取节点列表
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "系统管理-系统信息-客户端类型布置", logType = LogTypeEnum.业务日志, description = "获取节点数据列表", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getClientNodeTree", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getClientNodeTree(WebRequest request) {
        try {
            Data data = getParam(request);
            return this.ok(clientDBService.getClientNodeTree(data));
        } catch (Exception e) {
            e.printStackTrace( );
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 通过ID获取客户端集群信息
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "系统管理-系统信息-客户端类型布置", logType = LogTypeEnum.业务日志, description = "获取客户端集群信息", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getClientClusterById", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getClientClusterById(@RequestParam(value = "id", required = false) String id) {
        try {
            Data data = new Data( );
            data.put("id", id.substring(1));
            ClientDBCluster clientDBCluster = clientDBService.getClientClusterById(data);
            if (clientDBCluster != null) {
                return this.ok(clientDBCluster);
            } else {
                return this.error(Constant.SYSTEM_EXCEPTION, "查询失败，请检查网络");
            }
        } catch (Exception e) {
            e.printStackTrace( );
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 保存集群信息
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "系统管理-系统信息-客户端类型布置", logType = LogTypeEnum.业务日志, description = "修改客户端集群信息", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/updateClientCluster", method = RequestMethod.POST, produces = {"application/json", "application/xml"})
    public BaseResponse updateClientCluster(@Valid @RequestBody ClientDBClusterVi clientDBClusterVi, BindingResult bindingResult) {
        try {
            Data data = new Data( );
            data.put("id", clientDBClusterVi.getId( ).substring(1));
            data.put("name", clientDBClusterVi.getName( ));
            data.put("remark", clientDBClusterVi.getRemark( ));
            data.put("type", clientDBClusterVi.getType( ).substring(1));
            data.put("resrc_id", clientDBClusterVi.getResrc_id( ));
            Integer result = clientDBService.updateClientCluster(data);
            if (result > 0) {
                return this.ok(1);
            } else {
                return this.error(Constant.SYSTEM_EXCEPTION, "名称已存在");
            }
        } catch (Exception e) {
            e.printStackTrace( );
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }

    /**
     * 添加集群信息
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "系统管理-系统信息-客户端类型布置", logType = LogTypeEnum.业务日志, description = "新增客户端集群信息", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/addClientCluster", method = RequestMethod.POST, produces = {"application/json", "application/xml"})
    public BaseResponse addClientCluster(@Valid @RequestBody ClientDBClusterVi clientDBClusterVi, BindingResult bindingResult) {
        try {
            Data data = new Data( );
            data.put("name", clientDBClusterVi.getName( ));
            data.put("remark", clientDBClusterVi.getRemark( ));
            data.put("type", clientDBClusterVi.getType( ));
            if (clientDBClusterVi.getResrc_id( ) != null) {
                data.put("resrc_id", clientDBClusterVi.getResrc_id( ));
            }
            Integer result = clientDBService.addClientCluster(data);
            if (result > 0) {
                return this.ok(1);
            } else {
                return this.error(Constant.SYSTEM_EXCEPTION, "名称已存在");
            }
        } catch (Exception e) {
            e.printStackTrace( );
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 保存客户端信息
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "系统管理-系统信息-客户端类型布置", logType = LogTypeEnum.业务日志, description = "保存客户端信息", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/saveOrUpdateClient", method = RequestMethod.POST, produces = {"application/json", "application/xml"})
    public BaseResponse saveOrUpdateClient(@Valid @RequestBody ClientDBForClusterVi clientDBForClusterVi, BindingResult bindingResult) {
        try {
            Data data = new Data( );
            data.put("cluster_id", clientDBForClusterVi.getId( ).substring(1));
            data.put("ip", clientDBForClusterVi.getValue( ));
            Integer result = clientDBService.saveOrUpdateClient(data);
            if (result > 0) {
                return this.ok(1);
            } else {
                return this.error(Constant.SYSTEM_EXCEPTION, "该IP已存在其他集群下，新增失败");
            }
        } catch (Exception e) {
            e.printStackTrace( );
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 删除客户端信息
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "系统管理-系统信息-客户端类型布置", logType = LogTypeEnum.业务日志, description = "删除客户端信息", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/deleteClient", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse deleteClient(@RequestParam(required = false) String delId) {
        try {
            Data data = new Data( );
            data.put("ip", delId.substring(1));
            Integer result = clientDBService.deleteClient(data);
            if (result > 0) {
                return this.ok(1);
            } else {
                return this.error(Constant.SYSTEM_EXCEPTION);
            }
        } catch (Exception e) {
            e.printStackTrace( );
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 删除客户端集群信息（以及集群下的客户端）
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "系统管理-系统信息-客户端类型布置", logType = LogTypeEnum.业务日志, description = "删除客户端集群信息（以及集群下的客户端）", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/deleteClientCluster", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse deleteClientCluster(@RequestParam(required = false) String delId) {
        try {
            Data data = new Data( );
            data.put("id", delId.substring(1));
            Integer result = clientDBService.deleteClientCluster(data);
            if (result > 0) {
                return this.ok(1);
            } else {
                return this.error(Constant.SYSTEM_EXCEPTION);
            }
        } catch (Exception e) {
            e.printStackTrace( );
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 获得资源列表
     *
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "系统管理-系统信息-客户端类型布置", logType = LogTypeEnum.业务日志, description = "获得资源列表", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/getResourceLists", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse getResourceLists() {
        try {
            Data data = new Data( );
            data.put("resrcTypeCode", "016");
            List<Resrc> resrcs = dataManagerService.getResourceLists(data);
            List<CodeAndValue> codeAndValues = Lists.newArrayList( );
            for (Resrc resrc : resrcs) {
                codeAndValues.add(Resrc2CodeAndValue(resrc));
            }
            return this.ok(codeAndValues);
        } catch (Exception e) {
            e.printStackTrace( );
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 导出Excel
     */
    /**
     * 拖拽客户端
     */
    @LogAnnotation(module = "系统管理-系统信息-客户端类型布置", logType = LogTypeEnum.业务日志, description = "导出Excel", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/exportExcelForClientData", method = RequestMethod.GET)
    public BaseResponse exportExcelForClientData(HttpServletRequest request, HttpServletResponse response) {
        try {
            Data dataMap = new Data( );
            dataMap.put("fileName", "客户端集群导出文档" + new Date( ).getTime( ) + ".xlsx");
            dataMap.put("resrcTypeCode", "016");
            String filePath = clientDBService.exportExcelForClientData(dataMap);
            OutputStream os = response.getOutputStream( );
            try {
                response.reset( );
                response.setHeader("Content-Disposition", "attachment; filename=" + dataMap.get("fileName"));
                response.setContentType("application/download; charset=UTF-8");
                //response.setContentType("application/x-download;charset=utf-8");
                os.write(FileUtils.readFileToByteArray(new File(filePath)));
                os.flush( );
            } finally {
                if (os != null) {
                    os.close( );
                }
            }
            return this.ok(1);
        } catch (Exception e) {
            e.printStackTrace( );
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }


    /**
     * 导入Excel
     */
    @LogAnnotation(module = "系统管理-系统信息-客户端类型布置", logType = LogTypeEnum.业务日志, description = "导入Excel", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/importExcelForClientData", method = RequestMethod.POST, produces = {"application/json", "application/xml"})
    public BaseResponse importExcelForClientData(HttpServletRequest request,
                                                 @RequestParam(value = "file", required = false) MultipartFile file) {
        try {
            List<String> head = Lists.newArrayList("客户端IP", "所属客户端集群名称", "集群类型", "数据采集集群");
            List<List<String>> data = ExcelUtil.importExcelByIs(file.getInputStream( ), head, file.getOriginalFilename( ));
            Data dataMap = new Data( );
            dataMap.put("data", data);
            dataMap.put("head", head);
            //调用解析接口
            Integer result = clientDBService.importExcelForClientData(dataMap);
            return this.ok(result);
        } catch (Exception e) {
            e.printStackTrace( );
            return this.error(Constant.SYSTEM_EXCEPTION, e.getMessage( ));
        }
    }


    /**
     * ==========xutao========start=================
     */
    /**
     * 更新或创建服务配置
     *
     * @param record
     * @return
     * @throws Exception
     */
    @LogAnnotation(module = "系统管理-系统信息-邮件服务器", logType = LogTypeEnum.业务日志, description = "更新或创建服务配置", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/createOrModifySysEmailConfig", method = RequestMethod.POST, produces = {"application/json", "application/xml"})
    public BaseResponse createOrModifySysEmailConfig(@Valid @RequestBody SysEmailSerConfVi record, BindingResult bindingResult) {
        try {
            return this.ok(sysManagerService.createOrModifySysEmailConfig(record));
        } catch (Exception e) {
            e.printStackTrace( );
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }

    /**
     * 获取邮箱服务的配置信息
     *
     * @return
     */
    @LogAnnotation(module = "系统管理-系统信息-邮件服务器", logType = LogTypeEnum.业务日志, description = "获取邮箱服务的配置信息", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/findSysEmailConfig", method = RequestMethod.GET, produces = {"application/json", "application/xml"})
    public BaseResponse findSysEmailConfig() {
        try {
            return this.ok(sysManagerService.findSysEmailConfig( ));
        } catch (Exception e) {
            e.printStackTrace( );
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }

    /**
     * 验证配置的邮箱是否正确
     *
     * @return
     */
    @LogAnnotation(module = "系统管理-系统信息-邮件服务器", logType = LogTypeEnum.业务日志, description = "验证配置的邮箱是否正确", logLevel = LogLevelEnum.低)
    @RequestMapping(value = "/verifySysEmailSer", method = RequestMethod.POST, produces = {"application/json", "application/xml"})
    public BaseResponse verifySysEmailSer(@Valid @RequestBody SysEmailSerConfVi record, BindingResult bindingResult) {
        try {
            if (record != null && StringUtils.isEmpty(record.getTestEmail( ))) {
                return this.error(Constant.NAME_IS_EXIST, "测试邮箱地址不能为空！");
            }
            System.out.println(record.getHost());
            sysManagerService.verifySysEmailSer(record);
            return this.ok(true);
        } catch (MessagingException e) {
            e.printStackTrace( );
            String msg=e.getMessage();
            if(msg.startsWith("530")){
                return this.error("530","请打开邮箱发件服务权限验证，类似ssl");
            }else if(msg.startsWith("553")){
                return this.error("553","登录人和信封上的发送人不匹配");
            }else if(msg.startsWith("501")){
                return this.error("501","收件人邮箱格式错误");
            }else {
                return this.error("501","未知的邮件服务器");
            }

        } catch (Exception e) {
            e.printStackTrace( );
            return this.error(Constant.SYSTEM_EXCEPTION);
        }
    }

    /**
     * ==========xutao========end=================
     */


    public CodeAndValue Resrc2CodeAndValue(Resrc resrc) {
        CodeAndValue codeAndValue = new CodeAndValue( );
        codeAndValue.setCode(String.valueOf(resrc.getId( )));
        codeAndValue.setValue(resrc.getName( ));
        return codeAndValue;
    }
}
